package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Account;
import com.example.entity.Airorders;
import com.example.entity.Airticket;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.AirordersMapper;
import com.example.mapper.AirticketMapper;
import com.example.mapper.UserMapper;
import com.example.utils.TimeUtils;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 机票订单表业务处理
 **/
@Service
public class AirordersService {

    @Resource
    private AirordersMapper airordersMapper;
    @Resource
    private AirticketMapper airticketMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 新增
     */
    public void add(Airorders airorders) throws ParseException {
        airorders.setTime(DateUtil.now());
        airorders.setOrderNo(DateUtil.format(new Date(), "yyyyMMddHHmmss"));

        // 1. 判断一下机票的剩余数量
        Airticket airticket = airticketMapper.selectById(airorders.getTicketId());
        if (airticket.getNum() < airorders.getNum()) {
            throw new CustomException("-1", "当前机票数量不足");
        }
        // 2. 判断一下用户的余额够不够这个机票的费用
        Double price = airticket.getPrice() * airorders.getNum();
        User user = userMapper.selectById(airorders.getUserId());
        if (user.getAccount() < price) {
            throw new CustomException("-1", "您的余额不足，请到个人中心充值");
        }
        // 3. 判断一下当前天是否在起飞天之前
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (TimeUtils.compareDate(today, airorders.getBegin(), "yyyy-MM-dd")) {
            throw new CustomException("-1", "平台限定最早只能预订第二天的票");
        }
        airorders.setFlyTime(airorders.getBegin() + " " + airticket.getStartTime());
        airordersMapper.insert(airorders);

        // 4. 扣除用户的余额
        user.setAccount(user.getAccount() - price);
        userMapper.updateById(user);
        // 5. 扣掉这个机票的剩余数量
        airticket.setNum(airticket.getNum() - airorders.getNum());
        airticketMapper.updateById(airticket);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        airordersMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            airordersMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Airorders airorders) {
        airordersMapper.updateById(airorders);
    }

    /**
     * 根据ID查询
     */
    public Airorders selectById(Integer id) {
        return airordersMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Airorders> selectAll(Airorders airorders) {
        List<Airorders> list = airordersMapper.selectAll(airorders);
        for (Airorders dbOrders : list) {
            dbOrders.setTotal(dbOrders.getPrice() * dbOrders.getNum());
        }
        return list;
    }

    /**
     * 分页查询
     */
    public PageInfo<Airorders> selectPage(Airorders airorders, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Airorders> list = airordersMapper.selectAll(airorders);
        return PageInfo.of(list);
    }

    /**
     * 退票功能
     */
    public void returnTicket(Airorders airorders) throws ParseException {
        // 1. 判断当前的时间是否已经过了起飞的时间
        String now = DateUtil.now();
        String flyTime = airorders.getFlyTime();
        if (!TimeUtils.compareDate(flyTime, now, "yyyy-MM-dd HH:mm:ss")) {
            throw new CustomException("-1", "您的航班已经起飞，无法退票");
        }
        // 2. 退票
        airorders.setStatus("已退票");
        airordersMapper.updateById(airorders);
        // 3. 退钱
        User user = userMapper.selectById(airorders.getUserId());
        user.setAccount(user.getAccount() + airorders.getNum() * airorders.getPrice());
        userMapper.updateById(user);
        // 4. 票数返还
        Airticket airticket = airticketMapper.selectById(airorders.getTicketId());
        airticket.setNum(airticket.getNum() + airorders.getNum());
        airticketMapper.updateById(airticket);
    }

    /**
     * 改签功能
     */
    public void change(Airorders airorders) throws ParseException {
        // 获取今天的时间
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        if (TimeUtils.compareDate(today, airorders.getBegin(), "yyyy-MM-dd")) {
            throw new CustomException("-1", "平台限定最早只能改签第二天的票");
        }
        // 计算一下是否需要补差价或者退差价
        User user = userMapper.selectById(airorders.getUserId());
        double price = airorders.getNum() * airorders.getPrice();
        Integer ticketId = airorders.getTicketId();
        Airticket airticket = airticketMapper.selectById(ticketId);
        double nowPrice = airticket.getPrice() * airorders.getNum();
        if (price < nowPrice) {
            double gap = nowPrice - price;
            if (user.getAccount() < gap) {
                throw new CustomException("-1", "您的余额不足，请到个人中心充值");
            } else {
                // 用户补差价
                user.setAccount(user.getAccount() - gap);
                userMapper.updateById(user);
            }
        }
        if (price > nowPrice) {
            double gap = price - nowPrice;
            // 平台退差价
            user.setAccount(user.getAccount() + gap);
            userMapper.updateById(user);
        }
        // 更新一下改签后的订单信息
        airorders.setName(airticket.getName());
        airorders.setFlyTime(airorders.getBegin() + " " + airticket.getStartTime());
        airorders.setStartAirport(airticket.getStartAirport());
        airorders.setEndAirport(airticket.getEndAirport());
        airorders.setTimeSlot(airticket.getTime());
        airorders.setPrice(airticket.getPrice());

        airordersMapper.updateById(airorders);
    }
}